package org.mayuanxiaonong.timserver;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;

import org.mayuanxiaonong.timserver.codec.msgpack.MessagePackDecoder;
import org.mayuanxiaonong.timserver.codec.msgpack.MessagePackEncoder;
import org.mayuanxiaonong.timserver.config.Config;
import org.mayuanxiaonong.timserver.handler.ServerHandler;
import org.mayuanxiaonong.timserver.pack.msgpack.IPack;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Bootstrap {
	
	private static final Logger log = LoggerFactory.getLogger(Bootstrap.class);

	private static Bootstrap instance = null;
	
	private Config config = Config.getInstance();
	
	public Bootstrap() {
		if (instance != null) {
			throw new IllegalStateException("Server is already running");
		}
		instance = this;

		startup();
	}

	/**
	 * 启动服务
	 */
	public void startup() {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workGroup);
			b.channel(NioServerSocketChannel.class);
			b.option(ChannelOption.SO_BACKLOG, 128);
			b.option(ChannelOption.SO_KEEPALIVE, true);
			b.childHandler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel socketChannel) throws Exception {
					ChannelPipeline pipeline = socketChannel.pipeline();
					pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, IPack.HEAD_LENGTH_OFFSET, IPack.HEAD_LENGTH_LEN));
					pipeline.addLast(new MessagePackDecoder());
					pipeline.addLast(new LengthFieldPrepender(IPack.HEAD_LENGTH_LEN));
					pipeline.addLast(new MessagePackEncoder());
					pipeline.addLast(new ServerHandler());
				}
			});
			ChannelFuture future = b.bind(config.getServerHost(), config.getServerPort()).sync();
			future.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			log.error("Server startup failed", e);
			System.exit(1);
		} finally {
			bossGroup.shutdownGracefully();
			workGroup.shutdownGracefully();
		}
	}

}
